package com.me.test.controller;

import com.me.test.config.Wrapper;
import com.me.test.domain.User;
import com.me.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.List;

/**
 * @author ME
 * @date 2021/5/9
 */
@RestController
@RequestMapping(value = "/user")
public class UserMybatisController {

    private static final MessageFormat format = new MessageFormat(" {0} 条");

    @Autowired
    private UserService userService;

    /**
     * http://localhost:8888/user/user?id=4
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public User findUserById(User user) {
        return userService.findById(user.getId());
    }

    /**
     * http://localhost:8888/user/users2?age=13
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public Wrapper<List<User>> findUsers(User user) {
        System.out.println("开始查询...");
        final List<User> list = userService.findAll2(user.getName(), user.getAge());
        return Wrapper.ok("查询了" + format.format(new Object[]{list.size()}), list);
    }

    /**
     * http://localhost:8888/user/users2?name=Eli&age=12
     */
    @RequestMapping(value = "/users2", method = RequestMethod.GET)
    public Wrapper<List<User>> findUsers2(User user) {
        System.out.println("开始查询...");
        final List<User> list = userService.findAll(user);
        return Wrapper.ok("查询了" + format.format(new Object[]{list.size()}), list);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String insert(@RequestBody User user) {
        return "新增了" + format.format(new Object[]{userService.add(user)});
    }

    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public String update(@RequestBody User user) {
        return "更新了" + format.format(new Object[]{userService.update(user)});
    }

    @RequestMapping(value = "/del", method = RequestMethod.DELETE)
    public String delete(@RequestBody User user)  {
        return "删除了" + format.format(new Object[]{userService.del(user)});
    }

}
